/**
 * Notes: 兼职模块业务逻辑
 * Ver : CCMiniCloud Framework 2.0.1 ALL RIGHTS RESERVED BY cclinux0730 (wechat)
 * Date: 2024-03-23 04:00:00 
 */

const BaseProjectService = require('./base_project_service.js');
const dataUtil = require('../../../framework/utils/data_util.js');
const timeUtil = require('../../../framework/utils/time_util.js');
const util = require('../../../framework/utils/util.js');
const cloudUtil = require('../../../framework/cloud/cloud_util.js');
const MailModel = require('../model/mail_model.js');
const UserModel = require('../model/user_model.js');

class MailService extends BaseProjectService {

	// 获取当前状态
	getStatusDesc(mail) {
   let statusMap={
     0:"待接单",
     1:"已接单",
     9:"已完成"
   }
   let statusStr = statusMap[mail.MAIL_STATUS]

   if(mail.MAIL_STATUS==0&&mail.MAIL_END_TIME<this._timestamp){
    statusStr="已过期"
   }
   return statusStr;
	}

	/** 接单 */
	async acceptMail(userId, id) {
    let userName = await UserModel.getOneField({ USER_MINI_OPENID: userId }, 'USER_NAME');
    let updateData={
      MAIL_STATUS:1,
      MAIL_ACCEPT_USER_ID: userId,
      MAIL_ACCEPT_USER_NAME: userName,
      MAIL_ACCEPT_TIME: Date.now(), 
    }
    return await MailModel.insertOrUpdate({ _id: id },updateData)
	}

	/** 取消我的订单 */
	async cancelMail(userId, id) {
    let updateData={
      MAIL_STATUS:0,
      MAIL_ACCEPT_USER_ID: '',
      MAIL_ACCEPT_USER_NAME: '',
      MAIL_ACCEPT_TIME: 0, 
    }
    return await MailModel.insertOrUpdate({ _id: id },updateData)
	}

	/** 浏览 */
	async viewMail(id) {
		let fields = '*';

		let where = {
			_id: id,
			//MAIL_STATUS: 1
		}

		let mail = await MailModel.getOne(where, fields);
		if (!mail) return null;

		// 接单人信息
		if (mail.MAIL_STATUS > 0 && mail.MAIL_ACCEPT_USER_ID) {
			mail.acceptUser = await UserModel.getOne({ USER_MINI_OPENID: mail.MAIL_ACCEPT_USER_ID }, 'USER_NAME,USER_MOBILE');
		}

		MailModel.inc(id, 'MAIL_VIEW_CNT', 1);

		return mail;
	}

	/** 获取 */
	async getMailDetail(id) {
		return await MailModel.getOne(id);
	}

	/**修改状态 */
	async statusMail(userId, id, status) {
    //this.checkMy(id,userId)
    // 构造更新数据
    const updates = {
      MAIL_STATUS: status,
};

// 执行更新操作
return await MailModel.insertOrUpdate({ _id: id },  updates)
	}

	/** 删除 */
	async delMail(userId, id) {
		// 这里可以选择真正的删除或者标记为已删除
		await MailModel.del({ _id: id });
	
		return true;
  }
  
  async checkMy(id,userId){
    			// 验证邮件是否存在
			let mail = await MailModel.getOne({ _id: id });
			if (!mail) {
				throw new Error('邮件不存在');
			}
	
			// 检查是否是邮件的创建者或者是有权限修改的人
			if (mail.MAIL_USER_ID !== userId) {
				throw new Error('您没有权限编辑此邮件');
			}
  }
/**
 * 插入
 */
async insertMail(userId, {cateId,cateName,end,forms,order}) {
  try {
	   
	  let userName = await UserModel.getOneField({ USER_MINI_OPENID: userId }, 'USER_NAME');
      const data = {
          _pid: this.getProjectId(),
          //MAIL_ID: uniCloud.util.uniqueId(),
          MAIL_STATUS: 0, // 默认状态为待处理
          MAIL_END_TIME: timeUtil.time2Timestamp(end), // 如果需要设置截止时间，可以在后续逻辑中添加
          MAIL_CATE_ID: cateId, // 分类ID，根据实际情况设置
          MAIL_CATE_NAME: cateName, // 分类名称，根据实际情况设置
          MAIL_ORDER: order,
          MAIL_VOUCH: 0,
          MAIL_USER_ID: userId,
          MAIL_USER_NAME: userName, // 假设从 UserModel 中获取用户名
          MAIL_ACCEPT_USER_ID: '',
          MAIL_ACCEPT_USER_NAME: '',
          MAIL_ACCEPT_TIME: 0,
          MAIL_OVER_TIME: 0,
          MAIL_DAY: '', // 日期，如果需要设置日期，可以在后续逻辑中添加
          MAIL_FORMS: forms,
          MAIL_OBJ: dataUtil.dbForms2Obj(forms),
          MAIL_FAV_CNT: 0,
          MAIL_FAV_LIST: [],
          MAIL_VIEW_CNT: 0,
          MAIL_QR: '',
          MAIL_ADD_TIME: Date.now(),
          MAIL_EDIT_TIME: Date.now(),
          MAIL_ADD_IP: '', // IP 地址，可以从客户端获取
          MAIL_EDIT_IP: '' // IP 地址，可以从客户端获取
      };

      // 插入数据
      let id = await MailModel.insert(data);

      // 返回成功信息或数据
      return await MailModel.getOne(id);
  } catch (error) {
      console.error('[插入时发生错误]', error);
      throw new Error('插入时出现问题，请稍后再试或联系支持人员');
  }
}
	/** 修改 */
	async editMail(userId,{id,cateId,cateName,end,forms,order}) {
		try {
      //this.checkMy(id,userId)

			// 构造更新数据
       const updates = {
	           MAIL_END_TIME: timeUtil.time2Timestamp(end),
	           MAIL_CATE_ID: cateId,
	           MAIL_CATE_NAME: cateName,
	           MAIL_ORDER: order,
	           MAIL_FORMS: forms,
	           MAIL_OBJ: dataUtil.dbForms2Obj(forms),
	           MAIL_EDIT_TIME: Date.now(),
	           MAIL_EDIT_IP: '' // IP 地址，可以从客户端获取
	    };
	
			// 执行更新操作
			await MailModel.insertOrUpdate({ _id: id },  updates
	);
	
			// 返回更新后的邮件信息
			return await MailModel.getOne(id);
		} catch (error) {
			console.error('[编辑时发生错误]', error);
			throw new Error('编辑时出现问题，请稍后再试或联系支持人员');
		}
	}

	/** 更新forms信息 */
	async updateMailForms({
		id,
		hasImageForms
	}) {
			return await MailModel.editForms({_id:id},"MAIL_FORMS","MAIL_OBJ",hasImageForms,util.getProjectId());
	}

	/** 列表与搜索 */
	async getMailList(userId, {
		search, // 搜索条件
		sortType, // 搜索菜单
		sortVal, // 搜索菜单
		orderBy, // 排序
		whereEx, //附加查询条件
		page,
		size,
		isTotal = true,
		oldTotal }) {
		orderBy = orderBy || {
			'MAIL_ORDER': 'asc',
			'MAIL_ADD_TIME': 'desc'
		};
		let fields = 'MAIL_ACCEPT_USER_ID,MAIL_END_TIME,MAIL_STATUS,MAIL_ADD_TIME,MAIL_USER_ID,MAIL_OBJ';

		let where = {};
		where.and = {
			//MAIL_STATUS: 1,
			_pid: this.getProjectId() //复杂的查询在此处标注PID
		};


		if (util.isDefined(search) && search) {
			if (search == '我的发布') {
				where.and.MAIL_USER_ID = userId;
			}
			else if (search == '我的接单') {
				where.and.MAIL_ACCEPT_USER_ID = userId;
			}
			else if (search == '我的收藏') {
				where.and.MAIL_FAV_LIST = userId;
			}

			else {
				where.or = [
					{ 'MAIL_OBJ.title': ['like', search] },
					{ 'MAIL_OBJ.poster': ['like', search] },
					{ 'MAIL_OBJ.tel': ['like', search] },
				];
			}

		} else if (sortType && util.isDefined(sortVal)) {
			// 搜索菜单
			switch (sortType) {
				case 'cateId': {
					where.and.MAIL_CATE_ID = String(sortVal);
					break;
				}
				case 'status': {
					where.and.MAIL_STATUS = Number(sortVal);
					break;
				}
				case 'timeout': { //过期
					where.and.MAIL_STATUS = 0;
					where.and.MAIL_END_TIME = ['<', this._timestamp]
					break;
				}
				case 'wait': { //待接单
					where.and.MAIL_STATUS = 0;
					where.and.MAIL_END_TIME = ['>=', this._timestamp]
					break;
				}
				case 'sort': {
					orderBy = this.fmtOrderBySort(sortVal, 'MAIL_ADD_TIME');
					break;
				}
			}
		}

		return await MailModel.getList(where, fields, orderBy, page, size, isTotal, oldTotal);

	}

}

module.exports = MailService;